import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_pickers/more_pickers/init_data.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_pickers/style/default_style.dart';
import 'package:flutter_pickers/style/picker_style.dart';
import 'package:get/get.dart';
import 'package:ty_smart_watch/bean/user_detail_bean.dart';
import 'package:ty_smart_watch/common/images_url.dart';
import 'package:ty_smart_watch/page/me/controller/user_detail_controller.dart';
import 'package:ty_smart_watch/utils/Log.dart';

class UserDetailPage extends StatefulWidget {
  const UserDetailPage({super.key});

  @override
  State<UserDetailPage> createState() => _UserDetailPageState();
}

class _UserDetailPageState extends State<UserDetailPage> {
  final UserDetailController _controller = Get.put(UserDetailController());

  final int NICK_NAME = 10;
  final int AVATAR_URL = 11;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: const Text("用户设置"),
        centerTitle: true,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () {
            Get.back();
          },
        ),
      ),
      body: Column(
        children: [
          //头像
          Align(
            alignment: Alignment.center,
            child: Obx(
              () => Image.asset(_controller.avatarUrl.value, width: 100, height: 100),
            ),
          ),
          const SizedBox(height: 20),
          //名称
          Align(
            alignment: Alignment.center,
            child: GestureDetector(
              onTap: () {
                _nickNameDialog();
              },
              child: Obx(
                () => Text(
                  _controller.userName.value,
                  style: const TextStyle(fontSize: 18),
                ),
              ),
            ),
          ),
          const SizedBox(height: 20),
          Container(
            margin: const EdgeInsets.all(20),
            child: Obx(
              () => GridView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                    childAspectRatio: 1.5,
                    mainAxisSpacing: 10,
                    crossAxisSpacing: 10),
                itemCount: _controller.list.length,
                itemBuilder: (BuildContext context, int index) {
                  return GestureDetector(
                    onTap: () {
                      _clickItem(index, _controller.list[index]);
                    },
                    child: UserDetailItem(userDetail: _controller.list[index]),
                  );
                },
              ),
            ),
          ),
          const Expanded(child: SizedBox()),
          //设置新密码按钮
          GestureDetector(
            onTap: _controller.commit,
            child: Container(
              margin: const EdgeInsets.symmetric(horizontal: 20),
              height: 50,
              padding: const EdgeInsets.symmetric(vertical: 10),
              decoration: const BoxDecoration(
                //圆角半径
                borderRadius: BorderRadius.all(Radius.circular(50.0)),
                color: Color(0xFF2A6FE5),
              ),
              child: const Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    "完成",
                    style:
                        TextStyle(fontSize: 18, color: Colors.white, fontWeight: FontWeight.bold),
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 80),
        ],
      ),
    );
  }

  _clickItem(int index, UserDetailBean bean) {
    print('Clicked on ${bean.id}');
    List<String> sexList = ['男', '女'];
    String content = "";
    switch (bean.id) {
      case 0:
        Pickers.showSinglePicker(
          context,
          data: sexList,
          selectData: sexList[bean.data],
          pickerStyle: SexPickerStyle(),
          onConfirm: (p, position) {
            Log.d("性别选择结果:$p >> $position");
            _controller.updateData(bean.id, position);
          },
        );
        break;
      case 1:
        content = "请输入年龄";
        _itemContentDialog(index, bean, content);
        break;
      case 2:
        content = "请输入身高(cm)";
        _itemContentDialog(index, bean, content);
        break;
      case 3:
        content = "请输入体重(kg)";
        _itemContentDialog(index, bean, content);
        break;
    }
  }

  _itemContentDialog(int index, UserDetailBean bean, String content) {
    // showInputDialog(context);
    TextEditingController textController = TextEditingController();
    var res = "";
    Get.defaultDialog(
      title: bean.title,
      content: Column(
        children: [
          TextField(
            controller: textController,
            onChanged: (v) {},
            decoration: InputDecoration(
                hintText: content,
                hintStyle: const TextStyle(
                  color: Color(0xFF969696),
                ),
                border: InputBorder.none),
            keyboardType: TextInputType.number,
            inputFormatters: [
              FilteringTextInputFormatter.digitsOnly, //数字，只能是整数
            ],
            maxLines: 1,
          ),
        ],
      ),
      textConfirm: '确定',
      textCancel: '取消',
      onConfirm: () {
        // 用户点击确认按钮时执行的操作
        if (textController.text.isNotEmpty) {
          int mContent = int.parse(textController.text);
          _controller.updateData(bean.id, mContent);
        }
        Get.back();
      },
      onCancel: () {
        // 用户点击取消按钮时执行的操作
      },
    );
  }

  _nickNameDialog() {
    TextEditingController textController = TextEditingController();
    Get.defaultDialog(
      title: "昵称",
      content: Column(
        children: [
          TextField(
            controller: textController,
            onChanged: (v) {},
            decoration: const InputDecoration(
                hintText: "请输入昵称",
                hintStyle: TextStyle(
                  color: Color(0xFF969696),
                ),
                border: InputBorder.none),
            maxLines: 1,
          ),
        ],
      ),
      textConfirm: '确定',
      textCancel: '取消',
      onConfirm: () {
        // 用户点击确认按钮时执行的操作
        if (textController.text.isNotEmpty) {
          _controller.updateName(textController.text);
        }
        Get.back();
      },
      onCancel: () {
        // 用户点击取消按钮时执行的操作
      },
    );
  }
}

class UserDetailItem extends StatelessWidget {
  UserDetailItem({super.key, required this.userDetail});

  final UserDetailBean userDetail;
  final TextStyle _dataContentStyle = const TextStyle(fontSize: 16);

  @override
  Widget build(BuildContext context) {
    BoxDecoration decoration = BoxDecoration(
      //圆角半径
      borderRadius: const BorderRadius.all(Radius.circular(6.0)),
      // color: Color(userDetail.color),
      border: Border.all(color: const Color(0xFFE6E6E8), width: 1),
      // color: Colors.grey,
    );

    return Container(
      decoration: decoration,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          const SizedBox(height: 16),
          Text(userDetail.title, style: const TextStyle(fontSize: 16, color: Color(0xFF898996))),
          Expanded(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(_getData((userDetail)), style: _dataContentStyle),
                Container(width: 2),
                Text(userDetail.unit, style: _dataContentStyle),
              ],
            ),
          ),
          const SizedBox(height: 20),
        ],
      ),
    );
  }

  String _getData(UserDetailBean bean) {
    String res = "";
    switch (bean.id) {
      case 0:
        res = bean.data == 0 ? "男" : "女";
        break;
      case 1:
      case 2:
      case 3:
        res = bean.data < 0 ? "-" : bean.data.toString();
        break;
    }
    return res;
  }
}

/// 性别弹窗样式
class SexPickerStyle extends PickerStyle {
  SexPickerStyle({bool haveRadius = false, String? title}) {
    commitButton = Container(
      alignment: Alignment.center,
      padding: const EdgeInsets.only(left: 12, right: 22),
      child: const Text('确定', style: TextStyle(color: Colors.black, fontSize: 16.0)),
    );
  }
}
